package project.euler.honk.problem.to50;

public final class Problem49 {

	private static boolean isPrime(int number) {
		if (number == 1)
			return false;
		int max = (int) Math.sqrt(number);
		for (int i = 2; i <= max; i++)
			if (number % i == 0)
				return false;
		return true;
	}

	private static boolean isPerm(int a, int b) {
		char[] bChars = Integer.toString(b).toCharArray();
		int match = 0;
		while (a > 0) {
			int a_c = a % 10;
			for (int j = 0; j < bChars.length; j++) {
				if (a_c == bChars[j] - '0') {
					bChars[j] = 0;
					if (++match == 4)
						return true;
					else
						break;
				}
			}
			a = a / 10;
		}
		return false;
	}

	public static long solve() {
		for (int a = 1488;; a++) {
			int b = a + 3330;
			int c = b + 3330;
			if (c > 9999) {
				continue;
			} else if (isPerm(a, b) && isPerm(a, c) && isPrime(a) && isPrime(b) && isPrime(c)) {
				return 100000000L * a + 10000L * b + c;
			}
		}
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		long count = solve();
		long end = System.currentTimeMillis();
		System.out.println("Result: " + count + " Time: " + (end - start));
	}

}
